package com.xijia.wuyouwallet.activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.xijia.wuyouwallet.MyApp;
import com.xijia.wuyouwallet.R;
import com.xijia.wuyouwallet.api.MyCallBack;
import com.xijia.wuyouwallet.base.BaseActivity;
import com.xijia.wuyouwallet.bean.NewWestNoticeData;
import com.xijia.wuyouwallet.bean.SystemData;
import com.xijia.wuyouwallet.bean.UpVersionData;
import com.xijia.wuyouwallet.fragment.ExtendFragment;
import com.xijia.wuyouwallet.fragment.MeFragment;
import com.xijia.wuyouwallet.fragment.ReceiptFragment;
import com.xijia.wuyouwallet.fragment.WalletFragment;
import com.xijia.wuyouwallet.utils.FileUtil;
import com.xijia.wuyouwallet.utils.MyLogger;
import com.xijia.wuyouwallet.utils.UrlConfig;
import com.xijia.wuyouwallet.utils.XUtil;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/7/11 0011.
 */

public class HomeActivity extends BaseActivity implements View.OnClickListener{

    private Fragment mTab1, mTab2, mTab3, mTab4;
    //底部标题栏
    private LinearLayout bottom_fir;
    private ImageView bottom_fir_img;
    private TextView bottom_fir_txt;
    private LinearLayout bottom_two;
    private ImageView bottom_two_img;
    private TextView bottom_two_txt;
    private LinearLayout bottom_thr;
    private ImageView bottom_thr_img;
    private TextView bottom_thr_txt;
    private LinearLayout bottom_four;
    private ImageView bottom_four_img;
    private TextView bottom_four_txt;

    private LinearLayout home_top;

    private long mTochTime = 0;
    private long mWaitTime = 1000;

    //新添加版本更新功能
    private AlertDialog upVersioAlertDialog;
    private TextView dialog_upversion_main_sure;
    private TextView dialog_upversion_main_cancell;
    private WebView dialog_upversion_main_wv;
    private String downLoadUrl;

    //公告对话框
    private AlertDialog noticeAlertDialog;
    private TextView dialogNotice_content,dialogNotice_title;


    private ProgressDialog downloadProgress;//下载进度

    private String rid;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        initView();
        requestSysConfig();
        setTranslucentStatus();
        setSystemBarTintDrawable(R.color.main_orange);
        clearBottom();
        bottom_fir_img.setImageResource(R.mipmap.common_tab_btn_home_s);
        bottom_fir_txt.setTextColor(getResources().getColor(R.color.main_orange));
        selected(0);
        checkUersion();

        //requestNotice();
        //rid = JPushInterface.getRegistrationID(getApplicationContext());
        //bindJpush();

    }



    private void initView()
    {
        home_top = (LinearLayout) findViewById(R.id.home_top);
        bottom_fir = (LinearLayout) findViewById(R.id.bottom_fir);
        bottom_fir.setOnClickListener(this);
        bottom_fir_img = (ImageView) findViewById(R.id.bottom_fir_img);
        bottom_fir_txt = (TextView) findViewById(R.id.bottom_fir_txt);
        bottom_two = (LinearLayout) findViewById(R.id.bottom_two);
        bottom_two.setOnClickListener(this);
        bottom_two_img = (ImageView) findViewById(R.id.bottom_two_img);
        bottom_two_txt = (TextView) findViewById(R.id.bottom_two_txt);
        bottom_thr = (LinearLayout) findViewById(R.id.bottom_thr);
        bottom_thr.setOnClickListener(this);
        bottom_thr_img = (ImageView) findViewById(R.id.bottom_thr_img);
        bottom_thr_txt = (TextView) findViewById(R.id.bottom_thr_txt);
        bottom_four = (LinearLayout) findViewById(R.id.bottom_four);
        bottom_four.setOnClickListener(this);
        bottom_four_img = (ImageView) findViewById(R.id.bottom_four_img);
        bottom_four_txt = (TextView) findViewById(R.id.bottom_four_txt);
        //main_bottom_ll = (LinearLayout) findViewById(R.id.main_bottom_ll);
    }
    /**
     * 获取系统配置
     */
    private void requestSysConfig(){
        Map<String,Object> map = new HashMap<>();
        map.put("user",MyApp.userData.getData().getUser_id());
        map.put("token",MyApp.userData.getData().getToken());
        XUtil.Post(UrlConfig.GET_SYSTEM_CONFIG,map,new MyCallBack<String>(){

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                MyLogger.wLog().e("获取系统配置result="+result);
                MyApp.systemData = JSONObject.parseObject(result,SystemData.class);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                dismissProgressDialog();
                //MyLogger.wLog().e("获取系统配置onError="+ex.toString());
            }
        });
    }
    /**
     * 已登录绑定极光deviceId
     */
    private void bindJpush()
    {
        Map<String,Object> map = new HashMap<>();
        map.put("token",MyApp.userData.getData().getToken());
        map.put("user",MyApp.userData.getData().getUser_id());
        map.put("regId",rid);
        /*Log.e("info","bindJpush  " + "token="+MyApp.userData.getData().getToken());
        Log.e("info","bindJpush  " + "user="+MyApp.userData.getData().getUser_id());
        Log.e("info","bindJpush  " + "regId="+rid);*/
        XUtil.Post(UrlConfig.SAVE_JPUSH_ID_URL,map,new MyCallBack<String>(){

                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        MyLogger.wLog().e("绑定deviceID="+result);
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        MyLogger.wLog().e("绑定deviceIDonError="+ex.toString());
                    }
                });
    }
    private void initUpVersionDialog() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_upversion_main, null);
        dialog_upversion_main_sure = (TextView) view.findViewById(R.id.dialog_upversion_main_sure);
        dialog_upversion_main_sure.setOnClickListener(this);
        dialog_upversion_main_cancell = (TextView) view.findViewById(R.id.dialog_upversion_main_cancell);
        dialog_upversion_main_cancell.setOnClickListener(this);
        dialog_upversion_main_wv = (WebView) view.findViewById(R.id.dialog_upversion_main_wv);
        upVersioAlertDialog = new AlertDialog.Builder(this).setView(view).create();
    }
    private void initNoticeDialog() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_notice, null);
        TextView dialogNotice_config = (TextView) view.findViewById(R.id.dialogNotice_config);
        dialogNotice_config.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                noticeAlertDialog.dismiss();
            }
        });
        dialogNotice_content = (TextView) view.findViewById(R.id.dialogNotice_content);
        dialogNotice_title = (TextView) view.findViewById(R.id.dialogNotice_title);
        noticeAlertDialog = new AlertDialog.Builder(this).setView(view).create();
    }

    /**
     * 版本检测
     */
    private void checkUersion(){
        PackageManager pm = getPackageManager();
        int versionCode = 0;
        try {
            PackageInfo pi = pm.getPackageInfo(getPackageName(), 0);
            versionCode = pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        Map<String,Object> map = new HashMap<>();
        map.put("version_code",versionCode+"");
        //Log.e("info","getPackageName="+getPackageName());
        XUtil.Post(UrlConfig.UPDATE_VERSION_URL,map,new MyCallBack<String>(){

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                //MyLogger.wLog().e("版本更新result="+result);
                UpVersionData data = JSONObject.parseObject(result,UpVersionData.class);
                if (data.getCode()==200){
                    return;
                }else {
                    if (upVersioAlertDialog == null) {
                        initUpVersionDialog();
                    }
                    downLoadUrl = data.getData().getLink();
                    dialog_upversion_main_wv.getSettings().setDefaultTextEncodingName("utf-8");
                    dialog_upversion_main_wv.loadData(data.getData().getInfo(), "text/html; charset=UTF-8", null);
                    upVersioAlertDialog.setCanceledOnTouchOutside(false);
                    upVersioAlertDialog.setCancelable(false);
                    upVersioAlertDialog.show();
                }
            }


            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }
    //显示下载进度条
    private void showDownloadDialog(String url) {
        downloadProgress = new ProgressDialog(HomeActivity.this);
        downloadProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);// 设置水平进度条
        downloadProgress.setCancelable(false);// 设置是否可以通过点击Back键取消
        downloadProgress.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
        downloadProgress.setTitle("下载进度");
        downloadProgress.setMax(100);
        downloadProgress.setMessage("正在下载，请稍后...");
        downloadProgress.show();
        downloadNewVersion(url);
    }
    //下载
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            downloadProgress.dismiss();
            install();
        }
    };

    //**安装应用
    public void install() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/" + FileUtil.KonkaApplication + "/",
                "fuyingwallet.apk")), "application/vnd" + "" + ".android" + ".package-archive");
        startActivity(intent);
    }
    public void downloadNewVersion(final String url) {
        new Thread() {
            public void run() {
                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(url);
                try {
                    HttpResponse response = client.execute(get);
                    HttpEntity entity = response.getEntity();
                    long length = entity.getContentLength();
                    InputStream is = entity.getContent();
                    FileOutputStream fileOutputStream = null;
                    if (is != null) {
                        FileUtil.createFile("fuyingwallet.apk");
                        if (FileUtil.isCreateFileSucess == true) {
                            fileOutputStream = new FileOutputStream(FileUtil.updateFile);
                            byte[] b = new byte[1024];
                            int charb = -1;
                            long count = 0;
                            while ((charb = is.read(b)) != -1) {
                                fileOutputStream.write(b, 0, charb);
                                count += charb;
                                int progress = (int) (count * 100 / length);
                                downloadProgress.setProgress(progress);
                            }
                            downloadProgress.setProgress(100);
                            handler.sendEmptyMessage(1);
                        } else {
                            showToast("没有内存卡");
                            downloadProgress.dismiss();
                            return;
                        }
                    }
                    fileOutputStream.flush();
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
    private void setTranslucentStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window win = getWindow();
            WindowManager.LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            winParams.flags |= bits;
            win.setAttributes(winParams);

            home_top.setPadding(0,getStatusBarHeight(),0,0);
        }
    }

    //得到通知栏（状态栏）的高度
    private int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen",
                "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    private void setSystemBarTintDrawable(int resId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            SystemBarTintManager mTintManager = new SystemBarTintManager(this);
            if (resId != 0) {
                mTintManager.setStatusBarTintEnabled(true);
                mTintManager.setTintResource(resId);
            } else {
                mTintManager.setStatusBarTintEnabled(false);
                mTintManager.setTintDrawable(null);
            }
        }
    }
    /**
     * 获取最新公告
     */
    private void requestNotice(){
        XUtil.Post(UrlConfig.GET_NEWEST_NOTICE_URL,null,new MyCallBack<String>(){

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                MyLogger.wLog().e("获取最新公告result="+result);
                NewWestNoticeData newWestNoticeData = JSONObject.parseObject(result,NewWestNoticeData.class);
                if (newWestNoticeData.getCode()==200){
                    if (noticeAlertDialog == null) {
                        initNoticeDialog();
                    }
                    dialogNotice_title.setText(newWestNoticeData.getData().getList().getTitle());
                    dialogNotice_content.setText(newWestNoticeData.getData().getList().getContent());
                    noticeAlertDialog.show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                MyLogger.wLog().e("获取最新公告onError="+ex.toString());
            }
        });
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bottom_fir:
                clearBottom();
                bottom_fir_img.setImageResource(R.mipmap.common_tab_btn_home_s);
                bottom_fir_txt.setTextColor(getResources().getColor(R.color.main_orange));
                selected(0);
                break;
            case R.id.bottom_two:
                clearBottom();
                bottom_two_img.setImageResource(R.mipmap.common_tab_btn_vip_s);
                bottom_two_txt.setTextColor(getResources().getColor(R.color.main_orange));
                selected(1);
                break;
            case R.id.bottom_thr:
                clearBottom();
                bottom_thr_img.setImageResource(R.mipmap.common_tab_btn_generalize_s);
                bottom_thr_txt.setTextColor(getResources().getColor(R.color.main_orange));
                selected(2);
                break;
            case R.id.bottom_four:
                if (MyApp.userData==null){
                    jumpToPage(LoginActivity.class);
                    return;
                }
                clearBottom();
                bottom_four_img.setImageResource(R.mipmap.common_tab_btn_uc_s);
                bottom_four_txt.setTextColor(getResources().getColor(R.color.main_orange));
                selected(3);
                break;
            case R.id.dialog_upversion_main_sure:
                upVersioAlertDialog.dismiss();
                //showDownloadDialog(downLoadUrl);
                Intent intent = new Intent(Intent.ACTION_VIEW);    //为Intent设置Action属性
                intent.setData(Uri.parse(downLoadUrl)); //为Intent设置DATA属性
                startActivity(intent);
                break;
            case R.id.dialog_upversion_main_cancell:
                upVersioAlertDialog.dismiss();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (event.getAction() == KeyEvent.ACTION_DOWN && KeyEvent.KEYCODE_BACK == keyCode) {
            long currentTime = System.currentTimeMillis();
            if ((currentTime - mTochTime) >= mWaitTime) {
                showToast("请再按返回键退出应用！");
                mTochTime = currentTime;
            } else {
                finish();
               // MyActivityManager.getInstance().exit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    // 清除控件信息
    private void clearBottom() {
        bottom_fir_img.setImageResource(R.mipmap.common_tab_btn_home_n);
        bottom_two_img.setImageResource(R.mipmap.common_tab_btn_vip_n);
        bottom_thr_img.setImageResource(R.mipmap.common_tab_btn_generalize_n);
        bottom_four_img.setImageResource(R.mipmap.common_tab_btn_uc_n);
        bottom_fir_txt.setTextColor(getResources().getColor(R.color.font1));
        bottom_two_txt.setTextColor(getResources().getColor(R.color.font1));
        bottom_thr_txt.setTextColor(getResources().getColor(R.color.font1));
        bottom_four_txt.setTextColor(getResources().getColor(R.color.font1));
    }

    public void selected(int i) {
        FragmentManager fManager = getSupportFragmentManager();
        FragmentTransaction transaction = fManager.beginTransaction();
        hideFragment(transaction);
        switch (i) {
            case 0:
                if (mTab1 == null) {
                    mTab1 = new ReceiptFragment();
                    transaction.add(R.id.main_framlayoutId, mTab1);
                } else {
                    transaction.show(mTab1);
                }
                break;
            case 1:
                if (mTab2 == null) {
                    mTab2 = new WalletFragment();
                    transaction.add(R.id.main_framlayoutId, mTab2);
                } else {
                    transaction.show(mTab2);
                }
                break;
            case 2:
                if (mTab3 == null) {
                    mTab3 = new ExtendFragment();
                    transaction.add(R.id.main_framlayoutId, mTab3);
                } else {
                    transaction.show(mTab3);
                }
                break;
            case 3:
                if (mTab4 == null) {
                    mTab4 = new MeFragment();
                    transaction.add(R.id.main_framlayoutId, mTab4);
                } else {
                    transaction.show(mTab4);
                }
                break;
            default:
                break;
        }
        transaction.commit();
    }
    private void hideFragment(FragmentTransaction transaction) {
        if (mTab1 != null) {
            transaction.hide(mTab1);
        }
        if (mTab2 != null) {
            transaction.hide(mTab2);
        }
        if (mTab3 != null) {
            transaction.hide(mTab3);
        }
        if (mTab4 != null) {
            transaction.hide(mTab4);
        }
    }

}
